import 'dart:async';
import 'dart:io';

import 'package:app_links/app_links.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/event_bus_utils.dart';
import 'package:bike_ride/common/util/language.dart';
import 'package:bike_ride/common/widget/global_notification_widget.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/main/application.dart';
import 'package:bike_ride/model/entrance/view/entrance_v.dart';
import 'package:bike_ride/model/main/view/main_v.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/page_route_observer.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

/// App初始化的第一个页面可能是 其他页面，比如 广告、引导页、登陆页面
enum AppInitState {
  /// 是App主体页面
  isAppMainPage,

  /// 不是主体页面
  noAppMainPage
}

/// 全局key
/// 获取全局context方式：navigatorKey.currentContext
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

/// 监听全局路由，比如获取 当前路由栈里 页面总数
PageRouteObserver? pageRouteObserver;

class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  StreamSubscription<Uri>? _linkSubscription;
  late String _languageCode;
  @override
  void initState() {
    super.initState();
    initDeepLinks();
    _languageCode = Language().locale;
    EventBusUtils.listen(Locale, (p0) {
      setState(() {
        _languageCode = Language().locale;
      });
    });
  }

  Future<void> initDeepLinks() async {
    // Handle links
    _linkSubscription = AppLinks().uriLinkStream.listen((uri) async{
      debugPrint('onAppLink: $uri');
      final params = uri.path.split(uri.host).last.split('/'); //[, slebei, 888800002]
      if(params.length>1){
        final result= await AccountManager.updateBrandCode(params[1]);
        if(result == false)return;
      }
      if(params.length>2 && AccountManager.isLogin){
        NavigatorUtil.push(navigatorKey.currentContext!, Routers.unLockView, arguments: params[2],replace: pageRouteObserver?.getRouteStackPath().last == Routers.unLockView);
      }else{
        NavigatorUtil.push(navigatorKey.currentContext!, Routers.appMainPage,clearStack: true);
      }
    });
  }

  @override
  void dispose() {
    _linkSubscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// 初始化 MediaQuery、PageRouteObserver
    pageRouteObserver ??= PageRouteObserver();
    return GlobalOperateProvider(
      child: MaterialApp(
        locale: Locale(_languageCode),
        debugShowCheckedModeBanner: false,
        navigatorObservers: [pageRouteObserver!],
        // 全局key
        navigatorKey: navigatorKey,
        // 使用路由找不到页面时，就会执行 onGenerateRoute
        onGenerateRoute: Routers.router.generator,
        theme: ThemeStyles.defaultTheme,
        // 添加本地化支持
        localizationsDelegates: const [
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
          var result = supportedLocales.where((element) => element.languageCode == locale?.languageCode);
          if (result.isNotEmpty) {
            return locale;
          }
          return Locale(Language().locale);
        },
        supportedLocales: const [
          Locale('zh', 'CN'), //简体中文
          Locale('en', 'US'), //英文
          Locale('ms', 'MS'), //马来西亚
          Locale('th', 'TH'), //泰国
          Locale('id', 'ID'), //印度尼西亚
        ],
        home: WillPopScope(
          onWillPop: () async {
            if (!Navigator.canPop(context)) {
              return false;
            }
            exit(0);
          },
          child: AppTransfer(
            initState: AccountManager.isFirstOpen
                ? AppInitState.noAppMainPage
                : AppInitState.isAppMainPage,
          ),
        ),
        builder: EasyLoading.init(),
      ),
    );
  }
}

/// 这个是用来中转的，比如初始化第一个启动的页面 可能是 广告、引导页、登陆页面，之后再从这些页面进入 App主体页面
class AppTransfer extends StatelessWidget {
  const AppTransfer({super.key, required this.initState});

  final AppInitState initState;

  @override
  Widget build(BuildContext context) {
    Widget child; // MaterialApp
    switch (initState) {
      case AppInitState.isAppMainPage:
        {
          child = const AppMainPage();
        }
        break;
      default:
        // 进入 广告、引导页 等等，再从这些页面进入 App首页
        child = const EntranceView();
    }
    return child;
  }
}
